<%@page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags"%>
<%-- <link rel="stylesheet" href="${pageContext.request.contextPath}/themes/bootstrap/easyui.css" />
<link rel="stylesheet" href="${pageContext.request.contextPath}/themes/icon.css" />
<link rel="stylesheet" href="${pageContext.request.contextPath}/icheck/skins/all.css" />
<link rel="stylesheet" href="${pageContext.request.contextPath}/css/main.css" />
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery.easyui.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/api.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/common.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/validate.js"></script> --%>
<%-- <script type="text/javascript" src="${pageContext.request.contextPath}/icheck/icheck.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/locale/easyui-lang-zh_CN.js"></script> --%>
<script type="text/javascript">
$(function() {
	var urlPrefix = "${pageContext.request.contextPath}/api/";
	var advImageAPI = new AdvImageAPI({
		urlPrefix : urlPrefix
	});
	
	//for debug
	//try{throw ''} catch(e){}
	
	initializeGrid();
	
	function initializeGrid() {
		
		$('#adv_image_toolbar #btn_preview').linkbutton({
            text: '预览',
            iconCls: 'icon-preview',
            disabled: true,
            onClick: function() {
                $('#win_preview').window('open');
            }
        });
        
        $('#adv_image_toolbar #btn_add').linkbutton({
            text: '追加',
            iconCls: 'icon-add',
            disabled: true,
            onClick: function() {
                $('#file_upload').filebox({
                    buttonText: '选择',
                    buttonAlign: 'left',
                    buttonIcon: 'icon-search',
                    required: true
                });
                $(':input[type="file"]').attr('accept', 'image/*');
                
                $('#win_upload_adv_image').window({
                    onOpen: function() {
                        $('#btn_cancel').linkbutton({
                            onClick: function() {
                                $('#win_upload_adv_image').window('close');
                            }
                        });
                        $('#btn_upload').linkbutton({
                            onClick: function() {
                                var uploadParam = {};
                                uploadParam.title = $('#title').textbox('getValue');
                                uploadParam.description = $('#description').textbox('getValue');
                                $('#upload_param').val(JSON.stringify(uploadParam));
                                $('#upload_form').form('submit', {
                                    onSubmit: function(){
                                        var isValid = $(this).form('validate');
                                        return isValid;
                                    },
                                    success: function(data){
                                        var uploadResult = $.parseJSON(data);
                                        if (uploadResult.status == 0 && uploadResult.result) {
                                            $('#adv_image_list').datagrid('reload');
                                        }
                                        $('#win_upload_adv_image').window('close');
                                    }
                                });
                            }
                        });
                    },
                    onClose: function() {
                        $('#upload_form').form('clear');
                    }
                });
                $('#win_upload_adv_image').window('open');
            }
        });
        
		$('#adv_image_list').datagrid({
	        url: '${pageContext.request.contextPath}/api/AdvImageSearchAPI.json',
	        columns: [[
	            {field:'title', title:'标题', width:120, align:'left', halign:'center', resizable:false},
	            {field:'description', title:'文字描述', width:200, align:'left', halign:'center', resizable:false},
	            {field:'path', title:'文件路径', width:302, align:'left', halign:'center', resizable:false},
	            {field:'width', title:'宽度', width:60, align:'right', halign:'center', resizable:false},
	            {field:'height', title:'高度', width:60, align:'right', halign:'center', resizable:false},
	            {field:'size', title:'文件大小', width:80, align:'right', halign:'center', resizable:false},
                {field:'opt', title:'操作', width:200, align:'center', halign:'center', resizable:false, formatter: function(value, row, index) {
                	return '<a id="btn_on" class="button_on" href="#">启用</a>&nbsp;<a id="btn_off" class="button_off" href="#">停用</a>&nbsp;<a id="btn_delete" class="button_delete" href="#">删除</a>';
                }}
	        ]],
	        fit: true,
	        striped: true,
	        rownumbers: true,
	        singleSelect: true,
	        autoRowHeight: false,
	        idField: 'image_id',
	        toolbar: '#adv_image_toolbar',
/* 	        queryParams: {
	            param: JSON.stringify({
	                use_flag: true
	            })
	        }, */
	        loadFilter: function(data) {
	            var datax = {
	            	total:0,
	            	rows:new Array()
	            };
	            if (data.images) {
	                datax.total = data.images.length;
	                datax.rows = data.images;
	            }
	            return datax;
	        },
	        onLoadSuccess: function(data) {
	        	
                if (data.total > 0) {
                	$('.button_on').linkbutton({
                        iconCls: 'icon-on',
                        onClick: function() {
                            var index = $(this).index('.button_on');
                            if (!data.rows[index].use_flag) {
                                imageOnOff(data.rows[index].image_id, true, {
                                    onSuccess: function() {
                                        $('#adv_image_list').datagrid('reload');
                                    }
                                });
                            }
                        }
                    });
                    
                    $('.button_off').linkbutton({
                        iconCls: 'icon-off',
                        onClick: function() {
                            var index = $(this).index('.button_off');
                            if (data.rows[index].use_flag) {
                                imageOnOff(data.rows[index].image_id, false, {
                                    onSuccess: function() {
                                        $('#adv_image_list').datagrid('reload');
                                    }
                                });
                            }
                        }
                    });
                    
                    $('.button_delete').linkbutton({
                        iconCls: 'icon-delete',
                        onClick: function() {
                            var index = $(this).index('.button_delete');
                            imageDelete(data.rows[index].image_id, {
                                onSuccess: function() {
                                    $('#adv_image_list').datagrid('reload');
                                }
                            });
                        }
                    });
                    
                	$.each(data.rows, function(index, row) {
                		if (row.use_flag) {
                			$('.button_on:eq(' + index + ')').linkbutton('disable');
                			$('.button_off:eq(' + index + ')').linkbutton('enable');
                		} else {
                			$('.button_on:eq(' + index + ')').linkbutton('enable');
                            $('.button_off:eq(' + index + ')').linkbutton('disable');
                		}
                	});
                	
                	$('#image_slider').remove();
                	$('#win_preview').append('<div id="image_slider"></div>');
                	$.each(data.rows, function(index, row) {
                	    if (row.use_flag) {
                	        $('#image_slider').append('<img id="image' + (index + 1) + '" src="' + row.image + '" title="' + row.title + '" alt="' + row.description + '">');
                	    }
                    });

                    initializePreview();
                    
                    if (data.total < 10) {
                    	$('#adv_image_toolbar #btn_add').linkbutton('enable');
                    } else {
                    	$('#adv_image_toolbar #btn_add').linkbutton('disable');
                    }
                    $('#adv_image_toolbar #btn_preview').linkbutton('enable');
                    
                    $('#adv_image_list').datagrid('fixRowHeight');
                } else {
                	$('#adv_image_toolbar #btn_add').linkbutton('enable');
                	$('#adv_image_toolbar #btn_preview').linkbutton('disable');
                }
	        }
	    });
	}
	
    function initializePreview() {
    	$("#image_slider").slidesjs({
            width: 1000,
            height: 200,
            start: 1,
            play: {
                active: false,
                effect: "slide",
                interval: 5000,
                auto: true,
                swap: false,
                pauseOnHover: true,
                restartDelay: 2500
            },
            navigation: {
                active: false
            },
            pagination: {
                active: false
            },
            effect: {
            	slide: {
            		speed: 1000
            	}
            }
        });
    }
    
    function imageOnOff(imageId, onOff, callback) {
        var paramData = {};
        paramData.image_id = imageId;
        paramData.use_flag = onOff;
        advImageAPI.update({
			onSuccess : function(data) {
			    if (callback) {
			        if (data.result) {
			            if (callback.onSuccess && typeof(callback.onSuccess) == "function") {
			                callback.onSuccess();
			            }
					} else {
					    if (callback.onError && typeof(callback.onError) == "function") {
			                callback.onError();
			            }
					}
			    }
			},
			onAPIError : function(status, errors) {
				$.messager.alert('<s:text name="title.error" />', '<s:text name="messages.error.9004" />');
			},
			onServerError : function(jqXHR, textStatus, errorThrown) {
				$.messager.alert('<s:text name="title.error" />', '<s:text name="messages.error.9004" />');
			}
		}, {
			param : JSON.stringify(paramData)
		});
    }
    
    function imageDelete(imageId, callback) {
        var paramData = {};
        paramData.image_id = imageId;
        advImageAPI.remove({
			onSuccess : function(data) {
			    if (callback) {
			        if (data.result) {
			            if (callback.onSuccess && typeof(callback.onSuccess) == "function") {
			                callback.onSuccess();
			            }
					} else {
					    if (callback.onError && typeof(callback.onError) == "function") {
			                callback.onError();
			            }
					}
			    }
			},
			onAPIError : function(status, errors) {
				$.messager.alert('<s:text name="title.error" />', '<s:text name="messages.error.9004" />');
			},
			onServerError : function(jqXHR, textStatus, errorThrown) {
				$.messager.alert('<s:text name="title.error" />', '<s:text name="messages.error.9004" />');
			}
		}, {
			param : JSON.stringify(paramData)
		});
    }

});
</script>
<table id="adv_image_list"></table>
<div id="adv_image_toolbar">
  <a id="btn_preview" href="#"></a>
  <a id="btn_add" href="#"></a>
</div>
<div id="win_preview" class="easyui-window" style="width:1014px;" title="预览" data-options="modal:true, closed:true, collapsible:false, minimizable:false, maximizable:false, resizable:false">
  <div id="image_slider"></div>
</div>
<div id="win_upload_adv_image" class="easyui-window" style="width:510px;height:280px;padding:10px;" title="上传图片" data-options="modal:true, closed:true, collapsible:false, minimizable:false, maximizable:false, resizable:false">
  <form id="upload_form" name="upload_form" action="${pageContext.request.contextPath}/file/AdvImageUploadAction.action" method="post" enctype="multipart/form-data" target="image_frame">
    <table id="audit_table" class="edit_table">
      <tr>
        <th width="60">标题</th>
        <td><input id="title" class="easyui-textbox" data-options="width:400" required maxlength="20"></td>
      </tr>
      <tr>
        <th>内容描述</th>
        <td><input id="description" class="easyui-textbox" data-options="width:400,height:100,multiline:true" required maxlength="50"></td>
      </tr>
      <tr>
        <th>文件</th>
        <td>
          <input id="file_upload" name="image" type="text" style="width:400px">
        </td>
      </tr>
    </table>
    <iframe width="0" height="0" id="image_frame" name="image_frame" style="border: none;"></iframe>
    <input type="hidden" id="upload_param" name="param" />
  </form>
  <div style="text-align: right; margin-top: 5px;">
    <a id="btn_upload" class="easyui-linkbutton" data-options="iconCls:'icon-upload'">上传</a>
    <a id="btn_cancel" class="easyui-linkbutton" data-options="iconCls:'icon-cancel'">取消</a>
  </div>
</div>
